package ru.nsu.fit.ws.send_question;

import ru.nsu.fit.shared.data_base_manager.DatabaseManager;
import ru.nsu.fit.shared.error_codes.ErrorCodes;

import javax.jws.HandlerChain;
import javax.jws.WebService;
import java.sql.SQLException;

import static ru.nsu.fit.shared.error_codes.ErrorCodes.*;

/**
 * Created by IntelliJ IDEA.
 * User: vtimofeev
 * Date: 11/19/12
 * Time: 9:58 PM
 * To change this template use File | Settings | File Templates.
 */
@WebService(endpointInterface = "ru.nsu.fit.ws.send_question.QuestionSender")
@HandlerChain(file= "handler-chain.xml")
public class QuestionSenderImpl implements QuestionSender{

    private static int ILLEGAL_QUESTION_ID = -1;
    private static int QUESTION_LENGTH_LIMIT = 140;

    @Override
    public QuestionOutput askQuestion(QuestionInput input) {

        long userSessionId = input.getUserSessionId();
        String questionText = input.getQuestionText();
        String[] questionOptions = input.getQuestionOptions();

        try {
            int userID = DatabaseManager.getUserId(userSessionId);

            if (userID < 0) {
                return createQuestionOutput(ILLEGAL_QUESTION_ID, NOT_AUTHORIZED);
            }

            if (questionText.length() > QUESTION_LENGTH_LIMIT) {
                return createQuestionOutput(ILLEGAL_QUESTION_ID, QUESTION_IS_TOO_LONG);
            }

            int questionId =
                    DatabaseManager.createQuestion(userID, questionText, questionOptions);
            return createQuestionOutput(questionId, NO_ERROR);
            
        } catch (SQLException e) {
            e.printStackTrace();
            return createQuestionOutput(ILLEGAL_QUESTION_ID, DATABASE_ERROR);
        }
    }

    private QuestionOutput createQuestionOutput(int questionId, ErrorCodes errorCode) {

        QuestionOutput questionOutput = new QuestionOutput();

        questionOutput.setQuestionId(questionId);
        questionOutput.setErrorCode(errorCode.getCode());
        questionOutput.setErrorMessage(errorCode.getMessage());

        return questionOutput;
    }
}
